'use client'

import { useRef, useEffect, forwardRef, useImperativeHandle } from 'react'
import { Box, useColorModeValue } from '@chakra-ui/react'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { QuillContent } from '@/types/chapter'
import { QuillEditorProps } from '@/types/editor/quill'

// 扩展Quill编辑器实例类型
export interface QuillEditorRef {
  getEditor: () => any;
}

export const QuillEditor = forwardRef<QuillEditorRef, QuillEditorProps>(({
  content,
  onChange,
  placeholder = 'Begin writing your story...',
  readOnly = false,
}, ref) => {
  const editorRef = useRef<ReactQuill>(null)
  const bgColor = useColorModeValue('white', 'gray.800')
  const textColor = useColorModeValue('gray.800', 'gray.100')
  
  // 暴露getEditor方法给父组件
  useImperativeHandle(ref, () => ({
    getEditor: () => editorRef.current?.getEditor()
  }));
  
  // 自定义Quill模块配置
  const modules = {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],
      [{ 'header': 1 }, { 'header': 2 }],
      ['blockquote'],
      [{ 'list': 'ordered' }, { 'list': 'bullet' }],
      [{ 'align': [] }],
      ['clean']
    ],
    clipboard: {
      matchVisual: false,
    },
    history: {
      delay: 1000,
      maxStack: 100,
      userOnly: true
    }
  }
  
  // 格式配置
  const formats = [
    'bold', 'italic', 'underline', 'strike',
    'header', 'blockquote', 'list', 'align'
  ]
  
  const handleChange = (content: string) => {
    try {
      // Quill可以返回HTML字符串，但我们需要转换为Delta格式存储
      const delta = editorRef.current?.getEditor().getContents()
      if (delta) {
        onChange(delta as unknown as QuillContent)
      }
    } catch (error) {
      console.error('Error updating content:', error)
    }
  }

  return (
    <Box
      className="quill-editor-container"
      sx={{
        '.ql-container': {
          border: 'none',
          fontSize: '18px',
          lineHeight: '1.8',
          fontFamily: 'Georgia, serif',
          color: textColor,
          backgroundColor: bgColor,
        },
        '.ql-editor': {
          padding: '0',
          minHeight: '300px',
        },
        // 隐藏工具栏（我们将使用自定义工具栏）
        '.ql-toolbar': {
          display: 'none',
        }
      }}
    >
      <ReactQuill
        ref={editorRef}
        theme="snow"
        value={typeof content === 'string' ? content : JSON.stringify(content)}
        onChange={handleChange}
        modules={modules}
        formats={formats}
        placeholder={placeholder}
        readOnly={readOnly}
      />
    </Box>
  )
})

QuillEditor.displayName = 'QuillEditor'; 